/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.bosc.marshall;

import com.acooly.core.utils.Reflections;
import com.acooly.core.utils.Strings;
import com.acooly.core.utils.net.HttpResult;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.api.util.Jsons;
import com.acooly.module.openapi.client.provider.bosc.BoscConstants;
import com.acooly.module.openapi.client.provider.bosc.domain.BoscResponse;
import com.acooly.module.openapi.client.provider.bosc.enums.BoscCodeEnum;
import com.acooly.module.openapi.client.provider.bosc.enums.BoscStatusEnum;
import com.acooly.module.safety.Safes;
import com.acooly.module.safety.signature.SignTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author zhangpu
 */
@Slf4j
@Component
public class BoscResponseUnmarshall extends BoscMarshallSupport implements ApiUnmarshal<BoscResponse, HttpResult> {
	
	
	@Resource(name = "boscMessageFactory")
	private MessageFactory messageFactory;
	
	@SuppressWarnings("unchecked")
	@Override
	public BoscResponse unmarshal (HttpResult message, String serviceName) {
		try {
			String plain = message.getBody ();
			String signature = message.getHeaders ().get (BoscConstants.SIGN);
			log.info ("响应报文:{}", message.getBody ());
			log.debug ("响应签名:{}", signature);
			
			BoscResponse boscResponse = (BoscResponse) messageFactory.getResponse (serviceName);
			boscResponse = Jsons.parse (plain, boscResponse.getClass ());
			boscResponse.setSign (signature);
			boscResponse.setService (serviceName);
			boscResponse.setPartner (getProperties ().getPlatformNo ());
			
			
			if (Strings.equals (boscResponse.getCode (), BoscCodeEnum.SUCCESS.getCode ())) {
				if (BoscStatusEnum.SUCCESS.equals (boscResponse.getStatus ())) {
					//只有成功才验签名
					Safes.getSigner (SignTypeEnum.Rsa.name ()).verify (plain, getKeyPair (), signature);
				} else {
					log.info ("远程系统返回:业务处理失败[code=0,status=INIT],不做验签处理.........");
				}
			} else {
				log.info ("远程系统返回:调用失败[code=1],不做验签处理........");
			}
			
			return boscResponse;
		} catch (Exception e) {
			throw new ApiClientException ("解析响应报文错误:" + e.getMessage ());
		}
	}
	
	
}
